// src/router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import Login from '../views/Login.vue'
import PublicActivitiesView from '../views/PublicActivitiesView.vue'
import PublicActivityDetailView from '../views/PublicActivityDetailView.vue'
import ActivityManagementView from '../views/ActivityManagementView.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/public-activities',
    name: 'public-activities',
    component: PublicActivitiesView
  },
  {
    path: '/public-activities/:id',
    name: 'public-activity-detail',
    component: PublicActivityDetailView
  },
  {
    path: '/activity-management',
    name: 'activity-management',
    component: ActivityManagementView,
    meta: { requiresAdmin: true }
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  const userRole = localStorage.getItem('userRole');

  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!userRole) {
      next({ name: 'login' });
    } else {
      next();
    }
  } else if (to.matched.some(record => record.meta.requiresAdmin)) {
    if (userRole !== 'admin') {
      alert('You do not have permission to access this page.');
      next({ name: 'home' });
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router